//
//  String+Emoticon.swift
//  表情字符串转表情
//
//  Created by lzing on 16/4/5.
//  Copyright © 2016年 LZING. All rights reserved.
//

import UIKit

extension String {
    func emoticonTextToEmoticonAttributeString(font : UIFont) -> NSAttributedString {
        // 获取表情微博文本里的表情
        let pattern = "\\[.*?\\]"
        let regular = try! NSRegularExpression(pattern: pattern, options: NSRegularExpressionOptions.DotMatchesLineSeparators)
        let results = regular.matchesInString(self, options: NSMatchingOptions(rawValue: 0), range: NSRange(location: 0, length: self.characters.count))
        // 将普通文本转换为属性文本,方便后面替换图片
        let resultAttributeString = NSMutableAttributedString(string: self)
        // 遍历结果替换
        for result in results.reverse() {
            let range = result.rangeAtIndex(0)
            // 查找到的表情名称
            let emoticonName = (self as NSString).substringWithRange(range)
            // 根据名称匹配
            if let emoticon = LZEmoticonPackageManager.emoticonNameToEmoticonModel(emoticonName) {
                let attribute = emoticon.emoticonModelToAttribute(font)
                // 将表情名称替换为表情图片属性文本
                resultAttributeString.replaceCharactersInRange(range, withAttributedString: attribute)
            }
        }
        return resultAttributeString
    }

}
